package com.dong.zk;

import org.apache.zookeeper.*;
import org.apache.zookeeper.data.ACL;
import org.apache.zookeeper.data.Stat;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;


import java.util.ArrayList;
import java.util.List;

/**
 * @author: dzj
 * @date 2018/10/10-10:30
 */
public class ZkNodeOperator implements Watcher {
    private ZooKeeper zk = null;
    public static final String zkServerPath = "10.0.109.142:2181";
    public static final Integer timeout=5000;
    public static Logger logger = LoggerFactory.getLogger(ZkNodeOperator.class);
    public ZooKeeper getZk() {
        return zk;
    }
    private String connectPath;

    public ZkNodeOperator() {
    }

    public ZkNodeOperator(String connectPath) {
        try {
            zk = new ZooKeeper(connectPath,timeout,new ZkNodeOperator());

        } catch (IOException e) {
            if(zk!=null) {
                try {
                    zk.close();
                } catch (InterruptedException e1) {
                    e1.printStackTrace();
                }
            }
            e.printStackTrace();
        }
    }


    public static void main(String[] args) throws InterruptedException, KeeperException {
        ZkNodeOperator zkNodeOperator = new ZkNodeOperator(zkServerPath);
       // zkNodeOperator.CreateZkNodeWithCallback("/dong2","dong2".getBytes(),ZooDefs.Ids.OPEN_ACL_UNSAFE);
     //   new Thread().sleep(5000);
        Stat stat = zkNodeOperator.getZk().setData("/dong2", "modify".getBytes(), 0);
        System.out.println("返回版本: "+stat.getVersion());



    }
    public String createZkNode(String path, byte[] data, List<ACL> acls) {
        String result = "";
        try {
           result = zk.create(path,data,acls,CreateMode.PERSISTENT);
            System.out.println("创建节点: \t"+result+" 成功");
        } catch (KeeperException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return result;
    }
    public void CreateZkNodeWithCallback(String path,byte[] data,List<ACL> acls) {
        String result = "";
         zk.create(path,data,acls,CreateMode.PERSISTENT,new CreateCallback(),"我是上下文");
    }
    public void process(WatchedEvent watchedEvent) {
        logger.warn("接受到事件通知: "+watchedEvent);

    }
}
